<?php

class BoundHelper {
	
	static function getItemsList($where='', $order='', $s=0, $l=0){
		if(!$order) $order = 'bound_id ASC, sno ASC';
		return Db::get('_BoundItems')->select()->where($where)->order($order)->limit($s, $l)->getAll();
	}
	static function getItemsCount($where=''){
		return Db::get('_BoundItems')->count()->where($where)->getCol();
	}
	
	/**
	 * 库存汇总，指定月份： 201106
	 */
	static function getItemsSummaryList($day1=null,$day2=null){
		if(!$day1) $day1 = '20110101';
		if(!$day2) $day2 = date('Ymd');
		$list = array();
                
                $tmp = (fetch_a_string('key'))?Ware::getList(WareHelper::makupFuzzyKey(fetch_a_string('key'))):Ware::getList();
		foreach($tmp as $k=>$v)
                {
                    $list[] = self::_getItemsSummary($v,$day1,$day2);
                }
                	
//		Debug::pre($list);
		return $list;
	}
        
       
	
	static function type2txt($type=null){
		static $ary = array(
			Bound::TYPE_CK	=> '采购入库',
			Bound::TYPE_YJ	=> '工程移交',
			Bound::TYPE_TL	=> '退料入库',
			Bound::TYPE_PY	=> '盘盈调入',
			Bound::TYPE_LL	=> '领料出库',
			Bound::TYPE_PK	=> '盘亏调出',
		);
		if(null===$type) return $ary;
		return isset($ary[$type]) ? $ary[$type] : '';
	}

	static function getInTypes(){
		return array(
			Bound::TYPE_CK	=> '采购入库',
			Bound::TYPE_YJ	=> '工程移交',
			Bound::TYPE_TL	=> '退料入库',
			Bound::TYPE_PY	=> '盘盈调入',
		);
	}
	static function getOutTypes(){
		return array(
			Bound::TYPE_LL	=> '领料出库',
			Bound::TYPE_PK	=> '盘亏调出',
		);
	}
	
	static function getDetail($id){
		if($bound=Bound::get($id)){
			$bound['items'] = BoundItems::getByBound($id);
			return $bound;
		}
		return false;
	}
        
        static private function _getItemsSummary($arr,$day1,$day2)
        {          
            $addtime2 = strtotime($day2);
            $list = array();
            $tmp  = Db::get('BoundItems')->select('ware_id,`class`,sno,name,`specific`,unit,brand,
				sum(total) as total,sum(amount) as amount,cast(sum(total)/sum(amount) as decimal(10,2)) as price')
				->where(" sum_day>={$day1} AND sum_day<={$day2} AND effect=1 AND ware_id={$arr['id']}") 
				->group('`class`,`ware_id`')->order('sno asc,ware_id asc')->getAll();
                
		foreach($tmp as $k=>$row){
                    
			//本期出/入库
			if(!isset($list[$row['ware_id']])){
				$list[$row['ware_id']] = array_intersect_key($row, array_flip(array('ware_id','sno','name','specific','unit','brand')));
			}
			$arr[$row['class']] = array_diff_key($row, $list[$row['ware_id']]);
			//期初结存
			$item = Db::get('BoundItems')->select('bl_total,total,bl_amount,amount,`class`')
					->where("sum_day>={$day1} AND sum_day<={$day2} AND effect=1 AND ware_id={$row['ware_id']}") 
					->order('addtime ASC')->limit(1)->getOne();
			if($item['class']=='in'){
				$data = array(
					'bl_total'	=> $item['bl_total']-$item['total'],
					'bl_amount'	=> $item['bl_amount']-$item['amount'],
				);
				$data['bl_price'] = $data['bl_amount']>0? $data['bl_total']/$data['bl_amount'] : 0;
			}
			else{
				$data = array(
					'bl_total'	=> $item['bl_total']+$item['total'],
					'bl_amount'	=> $item['bl_amount']+$item['amount'],
				);
				$data['bl_price'] = ($data['bl_amount'])>0?$data['bl_total']/$data['bl_amount']:0;
			}
			$arr['head'] = $data;
			//期末结存
			$item = Db::get('BoundItems')->select('bl_total,bl_amount,bl_price')
					->where("sum_day>={$day1} AND sum_day<={$day2} AND effect=1 AND ware_id={$row['ware_id']}")
					->order('addtime DESC')->limit(1)->getOne();
			$arr['tail'] = $item;
		}
                
                
                
            if(!isset($arr['tail']['bl_amount'])) $arr['tail']['bl_amount']=0; 
            if(!isset($arr['head']['bl_amount'])) $arr['head']['bl_amount']=0;  
            if(!isset($arr['in']['amount'])) $arr['in']['amount']=0; 
            if(!isset($arr['out']['amount'])) $arr['out']['amount']=0; 
            
            //与结存比较
            $_tmp = Ware::getbyid($arr['id']);

            if($_tmp['amount']!=$arr['tail']['bl_amount'] || $arr['tail']['bl_amount']!=$arr['head']['bl_amount']+$arr['in']['amount']-$arr['out']['amount']){
                //执行检查
                $arr = self::_fixErrorData($arr);
            }  
            unset($_tmp);  
            return $arr;      
           
        }
	
        
         
        /*数据自检并修正*/
        
        static private function _fixErrorData($data)
        {
            // ware_id           class     amount    bl_amount     addtime
            //$data['id']         in         20         20          
            //$data['id']         out        1          19
            // 
            
            $arr = Db::get('BoundItems')->select('class,amount,bl_amount,addtime')->where("ware_id={$data['id']}")->order('addtime ASC')->getAll();
            foreach($arr as $k=>$v)
            {
                if($k>0) //从第二行开始
                {
                    $tmp = ($v['class']=='in')?($arr[$k-1]['bl_amount']+$v['amount']):($arr[$k-1]['bl_amount']-$v['amount']);
                    if($v['bl_amount']!=$tmp)
                    {
                        $arr[$k]['bl_amount']=$tmp;
                        Db::get('BoundItems')->update("bl_amount = {$tmp}")->where("ware_id={$data['id']} AND addtime={$v['addtime']} LIMIT 1")->exec();
                    }                    
                }
                else
                {
                   if($v['bl_amount']!=$v['amount'])
                   {
                       $arr[$k]['bl_amount']=$v['amount'];
                       Db::get('BoundItems')->update("bl_amount = {$v['amount']}")->where("ware_id={$data['id']} AND addtime={$v['addtime']} LIMIT 1")->exec();
                   }
                }
                
            }
            unset($arr);
            $data['tail']['bl_amount']=$data['head']['bl_amount']+$data['in']['amount']-$data['out']['amount'];
            return $data;
        }
}

?>
